package web;

import beans.LoginStatus;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import utils.CookieUtils;
import utils.ResultUtils;

import java.io.IOException;

/**
 * 处理登出操作
 */
@WebServlet("/user/logout")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //销毁会话状态
        request.getSession().invalidate();

        //同时销毁自动登录所生成的cookie
        Cookie cookie = CookieUtils.getCookie("autoLogin", request.getCookies());
        if (cookie!=null) {
            //cookie存在再销毁cookie
            cookie.setMaxAge(0);//0代表删除
            cookie.setPath(cookie.getPath());
            response.addCookie(cookie);
        }

        //响应登出相关信息
        String responseData = ResultUtils.result(LoginStatus.LOGGED_OUT, null);

        response.getWriter().write(responseData);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
